<?php

/**
 * @author Ta Van Chinh
 * @copyright 2013
 */

class UploadMulti{
   var $string_name = '';
   var $error = '';
   function UploadMulti($file_name,$file_path,$extend='',$size_alllow,$new_name =''){
      foreach($_FILES[$file_name]['tmp_name'] as $key => $tmp_name ){
         $new_file_name = $this->rename_image($new_name,$_FILES[$file_name]['name'][$key]); //$this->generate_name($_FILES[$file_name]['name'][$key]);
         $this->string_name .= $new_file_name.',';
         $file_size =$_FILES[$file_name]['size'][$key];
         $file_tmp =$_FILES[$file_name]['tmp_name'][$key];
         $file_type=$_FILES[$file_name]['type'][$key];	
         if($file_size > $size_alllow){
            $this->error ='File ảnh vượt quá dung lượng cho phép 2 MB';
         }		
         if(empty($this->error)==true){
            if(is_dir("$file_path/".$new_file_name)==false){
                move_uploaded_file($file_tmp,"$file_path/".$new_file_name);
            }else{									// rename the file if another one exist
                $new_dir="$file_path/".$new_file_name.time();
                 rename($file_tmp,$new_dir) ;				
            }	
         }
       }
       $this->string_name = substr($this->string_name,0,-1); // cắt dấu phảy cuối cùng
   }
   function rename_image($new_name,$filename){
      $name = '';
      $ext	= substr($filename, (strrpos($filename, ".") + 1));
      $name = str_replace(' ','-',removeAccent($new_name));
      $name .= '.' . $ext;
      return $name;
   }
   function generate_name($filename){
   	$name = "";
   	for($i=0; $i<3; $i++){
   		$name .= chr(rand(97,122));
   	}
   	$today= getdate();
   	$name.= $today[0];
   	$ext	= substr($filename, (strrpos($filename, ".") + 1));
   	return $name . "." . $ext;
   }
   function image_overlap($path, $filename){
		
		// Nếu tồn tại foreground thì mới overlap
		if(file_exists($this->foreground)){
			
			$background		= $this->create_image($path, $filename);
			if(!$background) return;
			
			// Chèn ảnh overlap vào
			$foreground		= imagecreatefrompng($this->foreground);
			$insertWidth	= imagesx($foreground);
			$insertHeight	= imagesy($foreground);
			$imageWidth		= imagesx($background);
			$imageHeight	= imagesy($background);
			$overlapX		= 5;
			$overlapY		= $imageHeight - $insertHeight - 5;
			
			imagecolortransparent($foreground, imagecolorat($foreground, 0, 0));
			imagecopy($background, $foreground, $overlapX, $overlapY, 0, 0, $insertWidth, $insertHeight);
			
			$this->output_image($background, $path, $filename);
			
			// Hủy biến để giải phóng bộ nhớ
			unset($background);
			unset($foreground);
			
		}
	}
   
}

?>